package com.ma.sharenote.usercenter.service.content;

import com.ma.sharenote.usercenter.dao.content.ShareMapper;
import com.ma.sharenote.usercenter.domain.dto.content.ShareDTO;
import com.ma.sharenote.usercenter.domain.dto.user.UserDTO;
import com.ma.sharenote.usercenter.domain.entity.content.Share;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class ShareService {

    private final ShareMapper shareMapper;

    private final RestTemplate restTemplate;

    private final DiscoveryClient discoveryClient;

    public ShareDTO findById(Integer id) {

        Share share = shareMapper.selectByPrimaryKey(id);
        /*
        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        List<String> url_list = instances.stream()
                .map(e -> e.getUri().toString() + "/users/{id}").collect(Collectors.toList());
        int index = ThreadLocalRandom.current().nextInt(url_list.size() - 1);
        String targetUrl = url_list.get(index);
        log.info("为服务的地址为{}",targetUrl);
        */
        //加入了Ribbon负载均衡 Ribbon会自动将下方user-center转换为注册的ip地址
        UserDTO userDTO =
                restTemplate.getForObject("http://user-center/users/{userId}",
                        UserDTO.class, share.getUserId());
        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share, shareDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());
        return shareDTO;
    }


}
